import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CommonService } from '../../../../services-common/common.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { storageOutOrderStateArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { PermissionService } from '../../../../service/permission.service';
import { ExwarehousmanageService } from '../../xstorage-manage-services/exwarehous-manage.service';

@Component({
  selector: 'app-storage-exwarehous-list',
  templateUrl: './storage-exwarehous-list.component.html',
  styleUrls: ['./storage-exwarehous-list.component.scss']
})
export class StorageExwarehousListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;
  @ViewChild('followUpRef') followUpRef: any;

  tabVal: number = 0;
  searchOptions: any = [
    { type: 1, labelText: '出库单号', valueKey: 'deliveryNumber', value: '' },
    { type: 1, labelText: '包含商品', valueKey: 'goods', value: '', placeholder: '编码/69码/名称' },
    { type: 1, labelText: '关联单号', valueKey: 'relationNum', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...storageOutOrderStateArrs]
    },
    {
      type: 2,
      labelText: '出库类型',
      valueKey: 'type',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '出库仓库',
      valueKey: 'whId',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '出库品质',
      valueKey: 'quality',
      value: '',
      multiple: false,
      notTostr: true,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '不良品'},
        {value: 1, label: '良品'}
      ]
    },
    { type: 3, labelText: '新建时间', valueKey: ['createTime', 'endTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  outTypeOptions: any[] = []; // 出库类型options
  warehouseOptions: any[] = []; // 仓库options

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };
  exportPickLoading = false;

  /**
   * 审核 Modal
   * ----------------------------------------------------------------
   */
  isExamineVisible = false;
  examineLoading = false;
  examineItem: any = {};
  auditOpinion: string = '';

  /**
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  isZfVisible = false;
  submitZfLoading = false;
  toVoidItem: any = {};
  toVoidRemark = ''; // 作废备注

  // 跟进 Modal
  initParams: any = {
    type: 4, // type 1、采购 2、SN 3、入库单 4、出库单
    relationInformation: ''
  };

  /**
   * ----------------------------------------------------------------
   * table check
   * ---------------------------------------------------------------- 
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();
  setOfCheckedArrs: any[] = [];

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      let checkedItem = this.listOfCurrentPageData.find(ele => ele.id === id);
      let setIds = this.setOfCheckedArrs.map(m => m.id);

      this.setOfCheckedId.add(id);
      if (!setIds.includes(id)) {
        this.setOfCheckedArrs.push({...checkedItem});
      }
    } else {
      let deleteIndex = this.setOfCheckedArrs.findIndex(ele => ele.id === id);

      this.setOfCheckedId.delete(id);
      this.setOfCheckedArrs.splice(deleteIndex, 1);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private modal: NzModalService,
    public permission: PermissionService,
    private storageCommonService: StorageCommonService,
    private services: ExwarehousmanageService
  ) { }

  ngOnInit(): void {
    this.loadOutTypeOptions();
    this.loadStoreOptions();
    this.setOfCheckedId.clear();
    this.setOfCheckedArrs = [];

    StorageExwarehousListComponent.updateCache = () => {
      this.setOfCheckedId.clear();
      this.setOfCheckedArrs = [];
      this.loadTable();
    }
  }

  // 出库类型options
  async loadOutTypeOptions() {
    const res: any = await this.commonService.getDictList('outbound_type');
    this.outTypeOptions = res || [];
    this.setSearchOption(res, 'type');
  }

  // 查询仓库Options
  async loadStoreOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
      this.setSearchOption(data.records, 'whId');
    } else {
      this.msg.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getExwarehousList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data.records || [];
      this.tableParams.total = data.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;

    this.setOfCheckedId.clear();
    this.setOfCheckedArrs = [];
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;

    this.tabVal = 0;
    this.setOfCheckedId.clear();
    this.setOfCheckedArrs = [];
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 合并单据
   * @returns 
   * ----------------------------------------------------------------
   */
  verifMergeOrderData() {
    console.log('ararrararrr', this.setOfCheckedArrs);
    // 状态是否存在 不等于 (审核通过 / 待打包 / 待出库)
    let isMergeState = this.setOfCheckedArrs.some(ele => ![2, 3, 4].includes(ele.state));
    // 配送方式是否存在 不为空
    let isMergeDeliveryMethod = this.setOfCheckedArrs.some(ele => !this.commonService.isEmpty(ele.deliveryMethod));

    if (this.setOfCheckedId.size < 2) {
      this.msg.warning('请至少选择2个单据');
      return false;
    } else if (isMergeState) {
      this.msg.warning('只有【审核通过 / 待打包 / 待出库】的单据才可以合并');
      return false;
    } else if (isMergeDeliveryMethod) {
      this.msg.warning('请先清空单据的配送信息再进行合并操作');
      return false;
    } else {
      return true;
    }
  }

  batchMergeListData() {
    this.msg.warning('功能待完善');
    return
    if (!this.verifMergeOrderData()) {
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '系统将会保留最早的一个单据而作废其他单据，确定合并单据?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        console.log('合并单据');
        let params = {
          ids: [...this.setOfCheckedId]
        }
        const {code, data, message}: any = await this.services.mergeExwarehousData(params);
        if (code === 0) {
          this.msg.success('操作成功');
          this.setOfCheckedId.clear();
          this.setOfCheckedArrs = [];
          this.loadTable();
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }
  
  /**
   * 通知出库 (type: 3) | 打包完成 (type: 4) | 确认出库 (type: 5) | 反审核 (type: 10) | 批量手动签收 (type: 6)
   * @param type 
   */
  async batchPperaInterface(type: number) {
    let params = {
      ids: [...this.setOfCheckedId],
      state: type,
      note: ''
    }

    const {code, data, message}: any = await this.services.auditExwarehousData(params);
    if (code === 0) {
      this.msg.success(data);
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 通知出库
   * @returns 
   */
  batchNoticeExwarehouse() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请选择所需操作项');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认通知仓库进行出库操作?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.batchPperaInterface(3);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 打包完成
   * @returns 
   */
  batchPackOver() {
    this.msg.warning('当前功能暂未开放!!!');
    return
    
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请至少选择1个单据');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认打包完成?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.batchPperaInterface(4);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 确认出库
   * @returns 
   */
  batchConfirmCk() {
    this.msg.warning('当前功能暂未开放!!!');
    return

    if (!this.setOfCheckedId.size) {
      this.msg.warning('请至少选择1个单据');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该操作不可逆，确认后库存将会减少，确认已经出库?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        await this.batchPperaInterface(5);
        this.setOfCheckedId.clear();
        this.setOfCheckedArrs = [];
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 反审核
   * @returns 
   */
  batchDeApprov() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请选择所需操作项');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '该操作不可逆，而且会清空已填写数据，确认反审核?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.batchPperaInterface(10);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * 作废 Modal
   * ----------------------------------------------------------------
   */
  showTovoidModal(item?: any) {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }

    this.toVoidRemark = '';
    this.isZfVisible = true;
  }

  async submitToVoidData() {
    if (this.commonService.isEmpty(this.toVoidRemark)) {
      this.msg.warning('请输入备注');
      return
    }

    let params = {
      ids: [...this.setOfCheckedId],
      state: 7, // 已作废
      note: this.toVoidRemark
    }
    this.submitZfLoading = true;
    const {code, data, message}: any = await this.services.auditExwarehousData(params);
    this.submitZfLoading = false;

    if (code === 0) {
      this.isZfVisible = false;
      this.msg.success(data);
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 批量手动签收
   * @returns 
   */
  batchManualSign() {
    console.log('selected arrs', this.setOfCheckedArrs);
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请选择所需操作项');
      return
    }

    // 请至少勾选1个待出库单据
    let isSignfor = this.setOfCheckedArrs.some(ele => ele.state === 5);
    if (!isSignfor) {
      this.msg.warning('请至少勾选1个已出库单据');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认手动签收?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.batchPperaInterface(6);
      },
      nzCancelText: '取消'
    });
  }

  // 单个签收
  async signforItem(item: any) {
    let params = {
      ids: [...item.id],
      state: 6,
      note: ''
    }

    const {code, data, message}: any = await this.services.auditExwarehousData(params);
    if (code === 0) {
      this.msg.success(data);
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * 通知快递取件
   * @returns 
   */
  noticeTakeParts() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请选择所需操作项');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认通知快递取件?',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ids: [...this.setOfCheckedId]
        }
    
        const {code, data, message}: any = await this.services.notifyPickupData(params);
        if (code === 0) {
          this.msg.success(data);
          this.loadTable();
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * 导出拣货信息
   * @returns 
   */
  async exportPickData() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请选择所需导出项');
      return
    }
    
    let params = {
      ids: [...this.setOfCheckedId].join(',')
    }

    this.exportPickLoading = true;
    const res: any = await this.services.exportExwarehousPickData(params);
    this.exportPickLoading = false;

    if (res.type === 'application/octet-stream') {
      this.commonService.downLoadBlobFile(res, '出库单拣货信息');
    } else {
      this.msg.error('导出失败');
    }
  }

  // 打印快递面单
  printOutOrder() {
    this.msg.warning('调试中...');
  }

  /**
   * 删除
   * @returns 
   */
  async deleteItem(item: any) {
    let params = {
      id: item.id
    }
    const {code, message}: any = await this.services.deleteExwarehousData(params);
    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  // 提交审核
  async submitReview(item: any) {
    let params = {
      ids: [item.id],
      state: 1,
      note: ''
    }
    const {code, message}: any = await this.services.auditExwarehousData(params);
    if (code === 0) {
      this.msg.success('提交审核成功');
      this.loadTable();
    } else {
      this.msg.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal(item: any) {
    this.examineItem = item;
    this.auditOpinion = '';
    this.isExamineVisible = true;
  }

  async subExamine(type: number) {
    if (type === 9 && this.commonService.isEmpty(this.auditOpinion)) {
      this.msg.warning('请输入审核意见');
      return
    }

    let params = {
      ids: [this.examineItem.id],
      state: type,
      note: this.auditOpinion
    }
    this.examineLoading = true;
    const res: any = await this.services.auditExwarehousData(params);
    this.examineLoading = false;

    if (res.code === 0) {
      this.isExamineVisible = false;
      this.msg.success('操作成功');
      this.loadTable();
    } else {
      this.msg.error(res.message);
    }
  }

  /**
   * other
   * ----------------------------------------------------------------
   */
  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(arrs: Array<any>, keyVal: any, idKey: string) {
    let tempObjs: any = {};
    if (arrs.length) {
      tempObjs = arrs.find(item => item[idKey] == keyVal);
    }

    return tempObjs?.name || '-';
  }

  copyText(str: any) {
    this.commonService.copyStr(str);
  }

  tabChange(val: any) {
    // 进行中: 待审核、审核通过、待打包、待出库
    let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'state');
    this.searchOptions[temIndex].value = val === 1 ? [1, 2, 3, 4] : [];
    this.searchParams.state = val === 1 ? '1,2,3,4' : '';

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }
}
